<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
      <el-form-item label="用户ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="成为代理商时间" prop="upgradeAgentTime">
        <el-date-picker
          v-model="queryParams.upgradeAgentTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="代理商级别" prop="level">
        <!--        <el-option v-for="level in levelOptions" :key="level.id" :label="level.name" :value="level.id">-->
        <!--      <span class="flex items-center gap-x-8px">-->
        <!--        <el-avatar :src="level.icon" size="small" />-->
        <!--        {{ level.name }}-->
        <!--      </span>-->
        <!--        </el-option>-->
        <el-button v-for="level in levelOptions" :key="level.id"
                   @click="handleQuery(level.id)">
          {{ level.name }}
        </el-button>
        <!--        <el-date-picker-->
        <!--          v-model="queryParams.createTime"-->
        <!--          value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--          type="daterange"-->
        <!--          start-placeholder="开始日期"-->
        <!--          end-placeholder="结束日期"-->
        <!--          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"-->
        <!--          class="!w-240px"-->
        <!--        />-->
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="用户编号" align="center" prop="id" min-width="120px"/>
      <el-table-column label="昵称" align="center" prop="nickname" min-width="120px"/>
      <el-table-column align="center" label="用户级别" prop="levelName" width="120px"/>
      <el-table-column label="推广人数" align="center" prop="inviteeNum" width="120px"/>
      <el-table-column label="推广订单数量" align="center" prop="inviteeOrderNum"
                       min-width="110px"/>
      <el-table-column label="推广订单金额" align="center" prop="inviteeOrderAmountTotal"
                       min-width="110px">
        <template #default="scope">{{ scope.row.inviteeOrderAmountTotal || 0 }}元</template>
      </el-table-column>
      <el-table-column label="累计佣金" align="center" prop="distAmountTotal" min-width="110px">
        <template #default="scope">{{ scope.row.distAmountTotal || 0 }}元</template>
      </el-table-column>
      <el-table-column label="未提现金额" align="center" prop="notWithdrawDistAmountTotal"
                       min-width="100px"/>
      <el-table-column label="已提现金额" align="center" prop="withdrawnDistAmountTotal"
                       min-width="100px">
        <template #default="scope">{{ scope.row.withdrawnDistAmountTotal || 0 }}元</template>
      </el-table-column>
      <el-table-column label="已提现次数" align="center" prop="withdrawalCount"
                       min-width="100px"/>
      <el-table-column label="上级推广员编号" align="center" prop="inviteId" width="150px"/>

      <!--      <el-table-column label="推广资格" align="center" prop="brokerageEnabled" min-width="80px">-->
      <!--        <template #default="scope">-->
      <!--          <el-switch-->
      <!--            v-model="scope.row.brokerageEnabled"-->
      <!--            active-text="有"-->
      <!--            inactive-text="无"-->
      <!--            inline-prompt-->
      <!--            :disabled="!checkPermi(['trade:brokerage-user:update-bind-user'])"-->
      <!--            @change="handleBrokerageEnabledChange(scope.row)"-->
      <!--          />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column
        label="成为代理商时间"
        align="center"
        prop="upgradeAgentTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="推广员绑定时间"
        align="center"
        prop="inviteTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="150px" fixed="right">
        <template #default="scope">
          <el-dropdown
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="[
              'trade:brokerage-user:user-query',
              'trade:brokerage-user:order-query',
              'trade:brokerage-user:update-bind-user',
              'trade:brokerage-user:clear-bind-user'
            ]"
          >
            <el-button link type="primary">
              <Icon icon="ep:d-arrow-right"/>
              更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  command="openBrokerageUserTable"
                  v-if="checkPermi(['trade:brokerage-user:user-query'])"
                >
                  邀请人
                </el-dropdown-item>

                <el-dropdown-item
                  command="openBrokerageOrderTable"
                  v-if="checkPermi(['trade:brokerage-user:order-query'])"
                >
                  邀请人订单
                </el-dropdown-item>
                <el-dropdown-item
                  command="mySuperior"
                  v-if="checkPermi(['trade:brokerage-user:user-query'])"
                >
                  上级邀请人
                </el-dropdown-item>
                <el-dropdown-item
                  command="openUpdateBindUserForm"
                  v-if="checkPermi(['trade:brokerage-user:update-bind-user'])"
                >
                  修改代理商级别
                </el-dropdown-item>

              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 修改上级推广人表单 -->
  <UpdateBindUserForm ref="updateBindUserFormRef" @success="getList"/>
  <!-- 推广人列表 -->
  <BrokerageUserListDialog ref="brokerageUserListDialogRef"/>
  <!-- 推广订单列表 -->
  <BrokerageOrderListDialog ref="brokerageOrderListDialogRef"/>

  <Dialog v-model="dialogBindInviteInfo" title="上级邀请人" width="600">
    <div>
      <el-card shadow="never">
        <el-row>
          <el-col :span="9">
            <ElAvatar shape="square" :size="120" :src="invite.avatar || undefined"/>
          </el-col>
          <el-col :span="14">
            <el-descriptions :column="1">
              <el-descriptions-item>
                <template #label>
                  <descriptions-item-label label="ID" icon="ep:user"/>
                </template>
                {{ invite.id }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <descriptions-item-label label="昵称" icon="ep:user"/>
                </template>
                {{ invite.nickname }}
              </el-descriptions-item>
              <el-descriptions-item label="手机号">
                <template #label>
                  <descriptions-item-label label="手机号" icon="ep:phone"/>
                </template>
                {{ invite.mobile }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <descriptions-item-label label="注册时间" icon="ep:calendar"/>
                </template>
                {{ invite.createTime ? formatDate(invite.createTime) : '空' }}
              </el-descriptions-item>
              <!--              <el-descriptions-item>-->
              <!--                <template #label>-->
              <!--                  <descriptions-item-label label="最后登录时间" icon="ep:calendar"/>-->
              <!--                </template>-->
              <!--                {{ invite.loginDate ? formatDate(invite.loginDate) : '空' }}-->
              <!--              </el-descriptions-item>-->
            </el-descriptions>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import {dateFormatter, formatDate} from '@/utils/formatTime'
import * as BrokerageUserApi from '@/api/mall/trade/brokerage/user'
import * as UserApi from '@/api/member/user'


import {checkPermi} from '@/utils/permission'
import {fenToYuanFormat} from '@/utils/formatter'
import UpdateBindUserForm from '@/views/mall/trade/brokerage/user/UpdateBindUserForm.vue'
import BrokerageUserListDialog from '@/views/mall/trade/brokerage/user/BrokerageUserListDialog.vue'
import BrokerageOrderListDialog
  from '@/views/mall/trade/brokerage/user/BrokerageOrderListDialog.vue'
import * as LevelApi from "@/api/member/level";
import * as MpUserApi from "@/api/member/user";
import {DICT_TYPE} from "@/utils/dict";
import {DescriptionsItemLabel} from "@/components/Descriptions";

defineOptions({name: 'TradeBrokerageUser'})

// const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  bindUserId: null,
  levelId: '',
  createTime: []
})

let invite = reactive({
  avatar: '',
  nickname: '',
  mobile: '',
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
/** 上级邀请人信息弹窗是否开启 */
const dialogBindInviteInfo = ref(false)
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.agentListPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }

  let obj = await LevelApi.getSimpleLevelList()

  // console.log(obj.slice(1))
  levelOptions.value = obj.slice(1);
}

const levelOptions = ref([])


/** 搜索按钮操作 */
const handleQuery = (levelId?: string) => {
  queryParams.levelId = typeof (levelId) == 'object' ? '' : levelId
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleCommand = (command: string, row: BrokerageUserApi.BrokerageUserVO) => {
  switch (command) {
    case 'openBrokerageUserTable':
      openBrokerageUserTable(row.id)
      break
    case 'openBrokerageOrderTable':
      openBrokerageOrderTable(row.id)
      break
    case 'openUpdateBindUserForm':
      openUpdateBindUserForm(row)
      break
    case 'mySuperior'://我的上级邀请人
      openMySuperior(row.inviteId)
      break

  }
}

/** 打开推广人列表 */
const brokerageUserListDialogRef = ref()
const openBrokerageUserTable = (id: number) => {
  brokerageUserListDialogRef.value.open(id)
}

/** 打开推广订单列表 */
const brokerageOrderListDialogRef = ref()
const openBrokerageOrderTable = (id: number) => {
  brokerageOrderListDialogRef.value.open(id)
}

/** 打开表单：修改上级推广人 */
const updateBindUserFormRef = ref()
const openUpdateBindUserForm = (row: BrokerageUserApi.BrokerageUserVO) => {
  updateBindUserFormRef.value.open(row)
}


/** 推广资格：开通/关闭 */
// const handleBrokerageEnabledChange = async (row: BrokerageUserApi.BrokerageUserVO) => {
//   try {
//     // 二次确认
//     const text = row.brokerageEnabled ? '开通' : '关闭'
//     await message.confirm(`确认要${text}"${row.nickname}"的推广资格吗？`)
//     // 发起修改
//     await BrokerageUserApi.updateBrokerageEnabled({id: row.id, enabled: row.brokerageEnabled})
//     message.success(text + '成功')
//     // 刷新列表
//     await getList()
//   } catch {
//     // 异常时，需要重置回之前的值
//     row.brokerageEnabled = !row.brokerageEnabled
//   }
// }


/** 打开父级邀请人 */
const openMySuperior = async (id: number) => {
  const data = await MpUserApi.getUser(id)
  invite = data ? data : []
  dialogBindInviteInfo.value = true
}
/** 初始化 **/
onMounted(() => {
  getList()

})
</script>
